import React, {Component} from 'react'
import ReactCSSTransitionGroup from 'react-addons-css-transition-group' // ES6

// 功能描述：
// 1. 有文本框和按钮
// 2. 点击按钮，将文本添加到组件状态中进行保存
// 3. 调用子组件，将文本列表，当作属性传入到子组件中
export default class TodoList extends Component{
    constructor(props){
        super(props)
        this.state = {
            todoList :[{text:'沙发', id:'1234567890'}],
            txt:''
        }
    }

    getChildContext() {
        return {color: "lightcyan"};
    }

    render(){
        return <div>
            <div>
                <input type="text" value={this.state.txt} onChange={this.handleTxtChange}/>
                <button onClick={this.handleBtnClick}>Add</button>
            </div>
            <RenderList todoList={this.state.todoList}/>
        </div>
    }

    // 文本框改变事件
    handleTxtChange = (e)=>{
        var newVal = e.target.value;
        this.setState({'txt':newVal});
    }

    // 点击添加按钮的处理事件
    handleBtnClick = (e)=>{
        if(this.state.txt.trim().length<=0){
            return;
        }
        // 拼接新的list数组
        var newList = this.state.todoList.concat({text:this.state.txt, id:Date.now()});
        // 将新的数组保存到状态中
        this.setState({todoList:newList}, function(){
            // 清空文本框内容
            this.setState({txt:''});
        });
    }
}
TodoList.childContextTypes={
    color:React.PropTypes.string
}

// 1. 从props属性中，获取到传递进来的状态，渲染列表并返回
class RenderList extends Component{
    render(){
        console.log(this.context.color)
        const list = this.props.todoList.map((item, i) =>{
            return <li key={item.id} style={{background: this.context.color}}>{item.text}</li>
        });
        return <ul>
            <ReactCSSTransitionGroup
          transitionName="example"
          transitionAppear={true}
          transitionAppearTimeout={500}
          transitionEnterTimeout={500}
          transitionLeaveTimeout={300}>
          {list}
          {list}
        </ReactCSSTransitionGroup>
        </ul>
    }
}
RenderList.contextTypes = {
    color:React.PropTypes.string
}